package com.anjufang.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anjufang.entity.SourceUser;
import com.anjufang.entity.Task;
import com.anjufang.mapper.GroupDetailMapper;
import com.anjufang.mapper.SourceUserMapper;
import com.anjufang.service.user.UserExcelService;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.cache.CacheKey;
import com.anjufang.utils.cache.RedisGroups;
import com.anjufang.utils.cache.RedisUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserExcelServiceImpl extends ServiceImpl<SourceUserMapper, SourceUser> implements UserExcelService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SourceUserMapper sourceUserMapper;
    @Autowired
    private GroupDetailMapper groupDetailMapper;

    @Override
    public String importExcel(List<Object[]> dataList) {

        // 清除旧数据
        sourceUserMapper.deleteAll();
        groupDetailMapper.deleteAll();

        Task task = new Task();
        task.setTaskType(0);
        task.setCreateTime(new Date());
        task.setUpdateTime(new Date());
        task.insert();

        List<SourceUser> list = new ArrayList<>();
        int t_size = 0; // 特殊用户
        int p_size = 0; // 普通用户
        char c = ' ';
        for(Object[] obj : dataList) {
            SourceUser sourceUser = new SourceUser();
            sourceUser.setTaskId(task.getId());
            
            sourceUser.setUserName(StringUtils.removeBuffer(String.valueOf(obj[0]), c)); // 姓名
            sourceUser.setIdNumber(StringUtils.removeBuffer(String.valueOf(obj[1]), c)); // 身份证
            // 身份类型
            String type = String.valueOf(obj[2]);
            if (type.equals("普通")) {
                sourceUser.setType(0);
                p_size++;
            } else {
                sourceUser.setType(1);
                t_size++;
            }
            sourceUser.setCreateTime(new Date());
            sourceUser.setUpdateTime(sourceUser.getCreateTime());
           
            list.add(sourceUser);
        }
        if (list.size() > 0) {
            // 检查数据是否重复
            String msg = checkData(list);
            if (StringUtils.isNotBlank(msg)) {
                return msg;
            }
            super.insertBatch(list);
            createUserNoCache(1, t_size, "ONE_KEY"); 
            createUserNoCache(t_size + 1, t_size + p_size, "TWO_KEY");
        }
        return null;
    }

    private String checkData(List<SourceUser> list) {
        StringBuffer sb = new StringBuffer();
        Map<String, List<SourceUser>> collect = list.stream().collect(Collectors.groupingBy(SourceUser::getIdNumber));
        if (!collect.isEmpty()) {
            collect.entrySet().forEach(item -> {
                if (StringUtils.isNotBlank(item.getKey()) && CollectionUtils.isNotEmpty(item.getValue()) && item.getValue().size() > 1) {
                    sb.append(item.getKey() + ",");
                }
            });
        }
        return sb.toString();
    }
    
    private void createUserNoCache(int startNum, int endSize, String val) {

        List<Integer> numList = new ArrayList<>();
        for (int i = startNum; i <= endSize; i++) {
            numList.add(i);
        }
        // 打乱数据
        Collections.shuffle(numList);
        logger.info("UserExcelServiceImpl.createUserNoCache, 缓存用户随机抽签编号，数据：{}", JSON.toJSONString(numList));
        // 先清除旧缓存
        CacheKey key = new CacheKey(RedisGroups.CACHE_USER_NO_TWO_KEY);
        if(val.equals("ONE_KEY")) {
        	key = new CacheKey(RedisGroups.CACHE_USER_NO_ONE_KEY);
        }
        
        RedisUtil.delete(key);
        for(Integer i : numList) {
            RedisUtil.lpush(key, i);
        }
    }

}
